package com.zhijian.wharf.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.JsonUtil;
import com.zhijian.util.page.Page;
import com.zhijian.wharf.dao.EnvMonitorMapper;
import com.zhijian.wharf.entity.dto.EnvMonitorDataDto;
import com.zhijian.wharf.entity.po.EnvMonitor;
import com.zhijian.wharf.entity.vo.request.EnvMonitorSaveOrUpdateVo;
import com.zhijian.wharf.entity.vo.request.EnvMonitorSearchVo;
import com.zhijian.wharf.entity.vo.response.EnvMonitorVo;
import com.zhijian.wharf.service.EnvMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 环境监测业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-07-24 10:10:45
 */
@Slf4j
@Service
public class EnvMonitorServiceImpl implements EnvMonitorService {

    @Autowired
    private EnvMonitorMapper mapper;

    /**
     * 超时时间，单位毫秒
     */
    private int TIME_OUT = 1000 * 20;

    @Override
    public EnvMonitor selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public EnvMonitorVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(EnvMonitor envMonitor) {
        Date now = new Date();
        envMonitor.setCreateTime(now);
        envMonitor.setUpdateTime(now);
        return mapper.insert(envMonitor) > 0 ? envMonitor.getId() : 0L;
    }

    @Override
    public Long insertSelective(EnvMonitor envMonitor) {
        Date now = new Date();
        envMonitor.setCreateTime(now);
        envMonitor.setUpdateTime(now);
        return mapper.insertSelective(envMonitor) > 0 ? envMonitor.getId() : 0L;
    }

    @Override
    public boolean update(EnvMonitor envMonitor) {
        Date now = new Date();
        envMonitor.setUpdateTime(now);
        return mapper.updateByPrimaryKey(envMonitor) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(EnvMonitor record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(EnvMonitorSaveOrUpdateVo saveOrUpdateVo) {
        EnvMonitor envMonitor = new EnvMonitor();
        BeanUtils.copyProperties(saveOrUpdateVo, envMonitor);
        return this.insert(envMonitor) != 0;
    }

    @Override
    public boolean modify(EnvMonitorSaveOrUpdateVo saveOrUpdateVo) {
        EnvMonitor old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        EnvMonitor envMonitor = new EnvMonitor();
        BeanUtils.copyProperties(saveOrUpdateVo, envMonitor);
        return this.update(envMonitor);
    }

    @Override
    public EnvMonitorVo selectOne(EnvMonitorSearchVo envMonitorSearchVo) {
        return mapper.selectOne(envMonitorSearchVo);
    }

    @Override
    public Integer count(EnvMonitorSearchVo envMonitorSearchVo) {
        return mapper.count(envMonitorSearchVo);
    }

    @Override
    public List<EnvMonitorVo> selectList(EnvMonitorSearchVo envMonitorSearchVo) {
        return mapper.selectList(envMonitorSearchVo);
    }

    @Override
    public Page<EnvMonitorVo> selectPage(EnvMonitorSearchVo envMonitorSearchVo) {
        AssertUtil.check(Objects.isNull(envMonitorSearchVo.getPageNum()) || Objects.isNull(envMonitorSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(envMonitorSearchVo);
        //分页
        Page<EnvMonitorVo> page = new Page<>(true, count, envMonitorSearchVo.getPageNum(), envMonitorSearchVo.getPageSize());
        envMonitorSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<EnvMonitorVo> responseVos = this.selectList(envMonitorSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<EnvMonitor> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public int deleteByCondition(EnvMonitorSearchVo envMonitorSearchVo) {
        //慎重用此方法！！
        return mapper.deleteByCondition(envMonitorSearchVo);
    }

    @Override
    public List<EnvMonitorDataDto> selectEnvMonitorDataDtoList(String deviceId, String start, String end) {
        String url = String.format("https://env.jingkongyun.com:9089/api/sensorData/getDataByDeviceidAndTime?deviceid=%s&start=%s&end=%s",
                deviceId, start, end);
        //链式构建请求
        try {
            HttpResponse httpResponse = HttpRequest.get(url)
                    //超时，毫秒
                    .timeout(TIME_OUT)
                    .execute();
            String responseBody = httpResponse.body();
//            log.info("select EnvMonitorDataDto response body is {}", responseBody);
            try {
                return JsonUtil.toArray(responseBody, EnvMonitorDataDto.class);
            } catch (Exception e) {
                log.error("the response body of select EnvMonitorDataDto is not legal...", e.getMessage());
                e.printStackTrace();
                return null;
            }
        } catch (Exception e) {
            log.error("the request of select EnvMonitorDataDto cause error...", e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}